package cevent.source.cloudcenter.business.controller.client;/**
 * Created by Cevent on 2021/7/27.
 */

import cevent.source.cloudcenter.server.dto.*;
import cevent.source.cloudcenter.server.enums.ShortMessageUseEnum;
import cevent.source.cloudcenter.server.exception.BusinessException;
import cevent.source.cloudcenter.server.exception.BusinessExceptionCode;
import cevent.source.cloudcenter.server.service.MemberService;
import cevent.source.cloudcenter.server.service.ShortMessageService;
import cevent.source.cloudcenter.server.util.UUID8Util;
import cevent.source.cloudcenter.server.util.ValidatorUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author cevent
 * @description 客户端会员接口
 * @date 2021/7/27 17:41
 */
@RestController
@RequestMapping("/client/member")
public class ClientMemberController {
    private static final Logger LOG= LoggerFactory.getLogger(ClientMemberController.class);
    public static final String BUSINESS_NAME="客户端Member模块";

    @Autowired
    MemberService memberService;
    @Resource
    ShortMessageService shortMessageService;
    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public ResponseDataDto memberRegister(@RequestBody MemberDto memberDto){

        /*ValidatorUtil.requiredLength(memberDto.getName(), "姓名", 1, 255);*/
        ValidatorUtil.requiredLength(memberDto.getNickName(), "昵称", 2, 255);
        /*ValidatorUtil.requiredLength(memberDto.getIcon(), "头像", 3, 500);
        ValidatorUtil.requiredLength(memberDto.getWechatCode(), "微信二维码", 3, 500);*/
        ValidatorUtil.requiredEmpty(memberDto.getMobile(), "手机号");
        ValidatorUtil.requiredLength(memberDto.getMobile(), "手机号", 11, 11);
        //ValidatorUtil.requiredLength(memberDto.getEmail(), "邮箱", 3, 255);
        ValidatorUtil.requiredLength(memberDto.getPassword(), "密码", 3, 255);
       /* ValidatorUtil.requiredLength(memberDto.getIdentityNum(), "身份证号", 3, 255);
        ValidatorUtil.requiredLength(memberDto.getBankNum(), "银行卡号", 3, 50);
        ValidatorUtil.requiredLength(memberDto.getBankCard(), "银行卡", 3, 500);
        ValidatorUtil.requiredLength(memberDto.getRegisterId(), "注册IP", 3, 50);
        ValidatorUtil.requiredLength(memberDto.getMotto(), "座右铭", 3, 255);*/

        //密码二次加密:digestUtils摘要工具类
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));

        //增加短信验证码校验
        ShortMessageDto shortMessageDto=new ShortMessageDto();
        shortMessageDto.setMobile(memberDto.getMobile());
        shortMessageDto.setUse(ShortMessageUseEnum.REGISTER.getCode());
        shortMessageDto.setCode(memberDto.getShortMessageCode());
        shortMessageService.validShortMessageCode(shortMessageDto);

        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.memberRegister(memberDto));

        return responseData;
    }
    @PostMapping("/login")
    public ResponseDataDto memberLogin(@RequestBody MemberDto memberDto, HttpServletRequest httpServletRequest){
        ResponseDataDto responseData=new ResponseDataDto();

        //登录密码二次加密
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));
        String imgCodeToken=(String)redisTemplate.opsForValue().get(memberDto.getImgCodeToken());
        LOG.info("redis获取的imgCode Token：{} ,memberDto.getImgCode():{}",imgCodeToken,memberDto.getImgCode());

        if(StringUtils.isEmpty(imgCodeToken) || StringUtils.isEmpty(memberDto.getImgCode())){
            responseData.setSuccess(false);
            responseData.setResponseMsg("验证码已过期，或账号密码输入错误");
            return responseData;
        }

        if(!imgCodeToken.toLowerCase().equals(memberDto.getImgCode().toLowerCase())){
            responseData.setSuccess(false);
            responseData.setResponseMsg("验证码输入错误，请重新输入");
            return responseData;
        }else{
            //每次更新session/redis存储的ImgCodeToken（每次登录都不同）
            httpServletRequest.getSession().removeAttribute(memberDto.getImgCodeToken());
            redisTemplate.delete(memberDto.getImgCodeToken());
        }

        //保存ips
        MemberLoginDto memberLoginDto=memberService.saveLoginIp(memberDto,httpServletRequest);
        //保存ips完毕，生成登录token计入memberLoginDto
        String token= UUID8Util.getShortUUID();
        memberLoginDto.setToken(token);
        /*String mobile=memberLoginDto.getMobile();
        String secretMobile=mobile.substring(0,3)+"******"+mobile.substring(9,11);
        memberLoginDto.setMobile(secretMobile);*/
        if(!StringUtils.isEmpty(memberLoginDto.getIdentityNum())){
            String identityNum=memberLoginDto.getIdentityNum();
            String secretIdentityNum=identityNum.substring(0,3)+"*************"+identityNum.substring(16,18);
            memberLoginDto.setIdentityNum(secretIdentityNum);
        }
        //将memberLoginDto放入session
        httpServletRequest.setAttribute(Constants.MEMBER_LOGIN_INFO,memberLoginDto);
        //放入redis:3600s存储memberLoginDto
        redisTemplate.opsForValue().set(token, JSON.toJSONString(memberLoginDto),3600, TimeUnit.SECONDS);

        responseData.setResponseData(memberLoginDto);
        return responseData;
    }

    @GetMapping("/loginout/{token}")
    public ResponseDataDto memberLoginout(@PathVariable String token,HttpServletRequest request){
        ResponseDataDto responseData=new ResponseDataDto();
        request.getSession().removeAttribute(Constants.MEMBER_LOGIN_INFO);
        redisTemplate.delete(token);
        responseData.setResponseData("会员已退出登录");
        return responseData;
    }

    @PostMapping("/resetPWD")
    public ResponseDataDto memberPasswordReset(@RequestBody MemberDto memberDto){
        ResponseDataDto responseData=new ResponseDataDto();

        MemberDto memberMobile=memberService.getMemberPhone(memberDto.getMobile());
        if(memberMobile==null){
            throw new BusinessException(BusinessExceptionCode.MEMBER_MOBILE_ERROR);
        }else{
            ShortMessageDto shortMessageDto=new ShortMessageDto();
            shortMessageDto.setMobile(memberDto.getMobile());
            shortMessageDto.setCode(memberDto.getShortMessageCode());
            shortMessageDto.setUse(ShortMessageUseEnum.FORGET.getCode());
            //校验短信验证码
            shortMessageService.validShortMessageCode(shortMessageDto);
            //执行保存pwd
            LOG.info("传入的password1：{}",memberDto.getPassword());
            memberMobile.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));
            responseData.setResponseData(memberService.saveMemberPwd(memberMobile));
            return responseData;
        }
    }

    @PostMapping("/saveMember")
    public ResponseDataDto memberSaveSecret(@RequestBody MemberDto memberDto){
        ValidatorUtil.requiredLength(memberDto.getEmail(), "邮箱", 5, 20);
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.memberSaveSecret(memberDto));
        return responseData;
    }

    //保存头像
    //保存miniPicList
    @PostMapping("/saveIcon")
    public ResponseDataDto saveMemberIcon(@RequestBody ModulePicPathDto modulePicPathDto){
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.saveMemberIcon(modulePicPathDto));
        return responseData;
    }

    //保存基本信息
    @PostMapping("/saveBaseInfo")
    public ResponseDataDto saveBaseInfo(@RequestBody MemberDto memberDto){
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.saveBaseInfo(memberDto));
        return responseData;
    }
}
